package com.example.mq.mqserver.datacenter.Impl;

import com.example.mq.MqApplication;
import com.example.mq.mqserver.core.Binding;
import com.example.mq.mqserver.core.Exchange;
import com.example.mq.mqserver.core.ExchangeType;
import com.example.mq.mqserver.core.MSGQueue;
import com.example.mq.mqserver.datacenter.IDataBaseManager;
import com.example.mq.mqserver.datacenter.mapper.MetaMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * 通过这个类操作数据库
 */
@Slf4j
public class DataBaseManagerImpl implements IDataBaseManager {
    private MetaMapper metaMapper;


    @Override
    public void init() {
        metaMapper = MqApplication.context.getBean(MetaMapper.class);
        //  检查数据库是否存在
        if(!checkDBExists()) {
            //  不存在就建库建表
            File fileDir = new File("./data");
            fileDir.mkdirs();
            //  创建目录时，MyBatis 会自动建好数据库，只需要手动建表就行
            createTable();
            //  插入一个默认的交换机
            insertDefaultData();
            log.info("数据库初始化完成.");
        } else {
            log.info("数据库已存在.");
        }
    }
    private void insertDefaultData() {
        Exchange exchange = new Exchange("default", ExchangeType.DIRECT,
                true,false);
        metaMapper.deleteExchange(exchange);
        metaMapper.insertExchange(exchange);
    }
    private void createTable() {
        metaMapper.createExchangeTable();
        metaMapper.createQueueTable();
        metaMapper.createBindingTable();
    }
    private boolean checkDBExists() {
        File file = new File("./data.meta.db");
        return file.exists();
    }

    @Override
    public void destroyDB() {
        File file = new File("./data/meta.db");
        file.delete();
    }

    @Override
    public void insertExchange(Exchange exchange) {
        metaMapper.insertExchange(exchange);
    }
    @Override
    public void deleteExchange(Exchange exchange) {
        metaMapper.deleteExchange(exchange);
    }
    @Override
    public List<Exchange> selectAllExchange() {
        return metaMapper.selectAllExchange();
    }


    @Override
    public void insertQueue(MSGQueue queue) {
        metaMapper.insertQueue(queue);
    }
    @Override
    public void deleteQueue(MSGQueue queue) {
        metaMapper.deleteQueue(queue);
    }
    @Override
    public List<MSGQueue> selectAllQueue() {
        return metaMapper.selectAllQueue();
    }


    @Override
    public void insertBind(Binding binding) {
        metaMapper.insertBinding(binding);
    }
    @Override
    public void deleteBinding(Binding binding) {
        metaMapper.deleteBinding(binding);
    }
    @Override
    public List<Binding> selectAllBinding() {
        return metaMapper.selectAllBinding();
    }

}
